﻿@using BlazorDemo.Configuration
@inject DemoConfiguration Configuration
@inject NavigationManager NavigationManager

@{
    var siteMode = Configuration.GetConfigurationValue<bool>("SiteMode");
}

<DxTreeView @ref="@treeView"
            CssClass="sidebar-tree"
            NodeExpandCollapseAction="TreeViewNodeExpandCollapseAction.NodeClick"
            AllowSelectNodes="true"
            TextWrapEnabled="true"
            SelectionChanged="@SelectionChanged">
    <Nodes>
        @foreach (var demoPage in Pages) {
            var hideDemoInTree = demoPage.IsMaintenanceMode || demoPage.IsExternal && !siteMode;
            if (!hideDemoInTree) {
                <NavMenuLeaf Page="@demoPage"></NavMenuLeaf>
            }
        }
    </Nodes>
</DxTreeView>
@code {
    DxTreeView treeView;

    [Parameter]
    public IEnumerable<DemoPageBase> Pages { get; set; }

    protected override void OnInitialized() {
        NavigationManager.LocationChanged += OnLocationChanged;
    }
    protected override void OnAfterRender(bool firstRender) {
        UpdateSelection(NavigationManager.Uri, true);
    }
    void OnLocationChanged(object sender, LocationChangedEventArgs args) {
        UpdateSelection(NavigationManager.Uri, true);
    }
    void UpdateSelection(string currentUri, bool expandNodesToSelection) {
        treeView.SelectNode(n => {
            if(!string.IsNullOrEmpty(n.NavigateUrl) && (currentUri.EndsWith("/" + n.NavigateUrl) || currentUri == NavigationManager.BaseUri && n.NavigateUrl == "./")) {
                if(expandNodesToSelection)
                    ExpandToSelectedNode(n);
                return true;
            }
            return false;
        });
    }
    void ExpandToSelectedNode(ITreeViewNodeInfo selectedNode) {
        var nodes = treeView.GetNodesInfo(n => true);
        foreach(var node in nodes) {
            treeView.SetNodeExpanded(n => n == node, IsParentNode(node, selectedNode));
        }
    }
    bool IsParentNode(ITreeViewNodeInfo parentNode, ITreeViewNodeInfo node) {
        while(node != null) {
            if(node == parentNode)
                return true;
            node = node.Parent;
        }
        return false;
    }
    protected void SelectionChanged(TreeViewNodeEventArgs e) {
        if(e.Reason != NavigationItemStateChangeReason.ApiCall && string.IsNullOrEmpty(e.NodeInfo.NavigateUrl))
            UpdateSelection(NavigationManager.Uri, false);
    }
    public void Dispose() {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }
    protected override bool ShouldRender() {
        return false;
    }
}
